import basicAuth from 'basic-auth'
import jwt from 'jsonwebtoken'
import { Models } from '../common/typings/model'
import config from '../config/config'
import HttpErrors from "../core/HttpException"
interface Decode {
    scope: number,
    uid: string | number
}
export default class Auth {
    // public static level: Models.Level
    static async verifyToken(ctx: Models.Ctx,next:Function) {
        //检测token是否合法
        const userToken = ctx.header['authorization'] || ctx.cookies.get('authorization');
        let errMsg = 'token不合法'
        if(!userToken) {
            throw new HttpErrors.Forbbiden('无访问权限')
        }
        try { 
            var decode = jwt.verify(userToken, config.security.secretKey) as string | Decode
        } 
        catch(error) {
            // if(error.name == 'TokenExpiredError') {
            //     errMsg = 'token已过期'
            // }  
            // throw new HttpErrors.Forbbiden(errMsg) 
        }
        // if(typeof decode === 'object'){
        //     if(decode.scope < config.UserLevel.User) {
        //         errMsg = '权限不足'
        //         throw new HttpErrors.Forbbiden(errMsg)
        //     }
        //     // 保存uid和scope
        //     ctx.auth = {
        //         uid: decode.uid,
        //         scope: decode.scope
        //     }
        // } 
        // else {
        //     errMsg = '权限不足'
        //     throw new HttpErrors.Forbbiden(errMsg)
        // }
        await next()
        // try {
        //     jwt.verify(token, config.security.secretKey)
        //     return true
        // }
        // catch(error) {
        //     return false
        // }
    }
    static getUserId(token: string) {
        // const data = jwt.decode(token, {secret: config.security.secretKey})
        const data = jwt.verify(token, config.security.secretKey) as Decode
        if(typeof data === 'object' && !data.uid) {
            let errMsg = 'token已过期'
            throw new HttpErrors.Forbbiden(errMsg)    
        }
        else {
            return data.uid
        }
        
    }
    
}